package com.kafka_demo2;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.*;

public class MsgConsumer {

    private final static String TOPIC_NAME = "my-replicated-topic";
    private final static String CONSUMER_GROUP_NAME = "testGroup6";

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "node01:9092,node02:9092,node03:9092");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_GROUP_NAME);

        // 手动提交
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        // 创建Consumer对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        //设置订阅topics
        consumer.subscribe(Arrays.asList(TOPIC_NAME));
        // 指定消费分区（可选）
//        consumer.assign(Arrays.asList(new TopicPartition(TOPIC_NAME, 1)));

//        List<PartitionInfo> partitionInfos = consumer.partitionsFor(TOPIC_NAME);
//        consumer.assign(Arrays.asList(new TopicPartition(TOPIC_NAME, 0)));
//        consumer.seekToBeginning(Arrays.asList(new TopicPartition(TOPIC_NAME, 0)));

        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord record : records) {
                System.out.println(record.topic() + "----" + record.partition() + "----" + record.offset()
                        + "----" + record.key() + "----" + record.value());
            }
            consumer.commitSync();
            consumer.commitAsync(new OffsetCommitCallback() {
                @Override
                public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception exception) {
                    if (exception != null) {
                        Set<Map.Entry<TopicPartition, OffsetAndMetadata>> entries = offsets.entrySet();
                        for(Map.Entry<TopicPartition, OffsetAndMetadata> entry :entries) {
                            TopicPartition key = entry.getKey();
                            OffsetAndMetadata value = entry.getValue();
                        }
                    }
                }
            });
        }


    }

}
